<template>
  <div class="operation-log-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <!-- <h1>操作日志管理</h1> -->
      <el-button type="primary" icon="Refresh" @click="handleRefresh"> 刷新 </el-button>
    </div>

    <!-- 筛选条件区域 -->
    <el-card class="filter-card">
      <el-form :model="queryForm" inline label-width="80px" class="filter-form">
        <el-form-item label="用户ID">
          <el-input
            v-model="queryForm.userId"
            placeholder="请输入用户ID"
            clearable
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item label="操作类型">
          <el-select
            v-model="queryForm.operation"
            placeholder="请选择操作类型"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="op in operationTypes"
              :key="op.value"
              :label="op.label"
              :value="op.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="操作时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 350px"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery"> 查询 </el-button>
          <el-button @click="handleReset" style="margin-left: 10px"> 重置 </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 日志列表 -->
    <el-card class="log-table-card">
      <el-table :data="logList" border stripe v-loading="loading" element-loading-text="加载中...">
        <el-table-column prop="id" label="日志ID" width="180" align="center" />
        <el-table-column prop="userId" label="用户ID" width="180" align="center" />
        <el-table-column prop="userName" label="操作人" width="120" align="center" />
        <el-table-column prop="operation" label="操作类型" width="150" align="center" />
        <el-table-column prop="description" label="操作描述" min-width="200" />
        <el-table-column prop="ipAddress" label="IP地址" width="150" align="center" />
        <el-table-column
          prop="createdAt"
          label="操作时间"
          width="180"
          align="center"
          :formatter="formatDateTime"
        />
        <el-table-column label="操作" width="120" align="center">
          <template #default="scope">
            <el-button
              type="text"
              @click="handleViewDetail(scope.row.id)"
              :disabled="!scope.row.id"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination" v-if="totalCount > 0">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryForm.page"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="queryForm.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount"
        />
      </div>
    </el-card>

    <!-- 日志详情弹窗 -->
    <el-dialog v-model="detailVisible" title="日志详情" width="600px" :close-on-click-modal="false">
      <el-descriptions column="1" border>
        <el-descriptions-item label="日志ID">{{ currentLog.id }}</el-descriptions-item>
        <el-descriptions-item label="用户ID">{{ currentLog.userId }}</el-descriptions-item>
        <el-descriptions-item label="操作人">{{ currentLog.userName }}</el-descriptions-item>
        <el-descriptions-item label="操作类型">{{ currentLog.operation }}</el-descriptions-item>
        <el-descriptions-item label="操作描述">{{
          currentLog.description || '-'
        }}</el-descriptions-item>
        <el-descriptions-item label="IP地址">{{
          currentLog.ipAddress || '-'
        }}</el-descriptions-item>
        <el-descriptions-item label="用户代理">{{
          currentLog.userAgent || '-'
        }}</el-descriptions-item>
        <el-descriptions-item label="操作时间">{{
          formatDateTime(currentLog.createdAt)
        }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { operationLogApi } from '@/api'

// 状态管理
const loading = ref(false)
const logList = ref([])
const totalCount = ref(0)
const detailVisible = ref(false)
const currentLog = ref({})

// 查询条件
const queryForm = reactive({
  page: 1,
  pageSize: 10,
  userId: '',
  operation: '',
  startDate: null,
  endDate: null,
})

// 日期范围选择器（单独处理，便于格式转换）
const dateRange = ref([])

// 常见操作类型（可根据实际业务扩展）
const operationTypes = [
  { label: '用户登录', value: 'UserLogin' },
  { label: '用户登出', value: 'UserLogout' },
  { label: '创建菜单', value: 'CreateMenu' },
  { label: '编辑菜单', value: 'UpdateMenu' },
  { label: '删除菜单', value: 'DeleteMenu' },
  { label: '分配角色', value: 'AssignRole' },
]

// 页面加载时查询数据
onMounted(() => {
  fetchLogs()
})
const toUtc = (d) => new Date(d).toISOString()
// 监听日期范围变化，同步到查询条件
watch(dateRange, (newVal) => {
  if (newVal && newVal.length === 2) {
    queryForm.startDate = toUtc(newVal[0])
    queryForm.endDate = toUtc(newVal[1])
  } else {
    queryForm.startDate = null
    queryForm.endDate = null
  }
})

// 获取日志列表
const fetchLogs = async () => {
  try {
    loading.value = true
    console.log('获取操作日志，查询参数:', queryForm)
    const res = await operationLogApi.getList(queryForm)
    console.log('操作日志API响应:', res)

    // http.js已经返回了response.data，适配后端返回的分页结构（PagedResultDto）
    logList.value = res.items || []
    totalCount.value = res.totalCount || 0

    console.log('解析的日志数据:', {
      logCount: logList.value.length,
      totalCount: totalCount.value,
    })
  } catch (err) {
    console.error('获取日志失败:', err)
    ElMessage.error('获取日志失败：' + (err.response?.data?.message || err.message))
    logList.value = []
    totalCount.value = 0
  } finally {
    loading.value = false
  }
}

// 格式化日期时间
const formatDateTime = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
  })
}

// 查询按钮
const handleQuery = () => {
  queryForm.page = 1 // 重置到第一页
  fetchLogs()
}

// 重置按钮
const handleReset = () => {
  // 重置表单
  Object.assign(queryForm, {
    page: 1,
    pageSize: 10,
    userId: '',
    operation: '',
    startDate: null,
    endDate: null,
  })
  dateRange.value = []
  fetchLogs()
}

// 刷新按钮
const handleRefresh = () => {
  fetchLogs()
  ElMessage.success('已刷新日志列表')
}

// 查看详情
const handleViewDetail = async (id) => {
  try {
    loading.value = true
    console.log('获取日志详情，ID:', id)
    const res = await operationLogApi.getById(id)
    console.log('日志详情API响应:', res)

    // http.js已经返回了response.data，所以res本身就是数据
    currentLog.value = res || {}
    console.log('解析的日志详情:', currentLog.value)
    detailVisible.value = true
  } catch (err) {
    console.error('获取日志详情失败:', err)
    ElMessage.error('获取日志详情失败：' + (err.response?.data?.message || err.message))
  } finally {
    loading.value = false
  }
}

// 分页大小变化
const handleSizeChange = (size) => {
  queryForm.pageSize = size
  queryForm.page = 1
  fetchLogs()
}

// 当前页变化
const handleCurrentChange = (page) => {
  queryForm.page = page
  fetchLogs()
}
</script>

<style scoped>
.operation-log-container {
  padding: 20px;
  max-width: 1600px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.log-table-card {
  overflow: hidden;
}

.pagination {
  margin-top: 15px;
  text-align: right;
}

/* 适配小屏幕 */
@media (max-width: 1200px) {
  .filter-form {
    flex-direction: column;
    align-items: flex-start;
  }

  .filter-form .el-form-item {
    width: 100%;
  }
}
</style>
